package cn.ddiancan.auth.config;

import java.util.Set;

import cn.ddiancan.auth.service.resolver.XddBearerTokenResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class Oauth2ClientConfiguration {

    @Value("${xddcloud.auth.oauth2.white-path:}")
    private Set<String> whitePath;

    @Bean
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http, JwtDecoder jwtDecoder,
        OAuth2AuthorizationService oAuth2AuthorizationService) throws Exception {
        http.authorizeHttpRequests(
                requests -> requests.requestMatchers(whitePath.toArray(new String[]{})).permitAll() // 允许所有用户访问这些路径
                    .anyRequest().authenticated()).csrf(AbstractHttpConfigurer::disable) // 禁用CSRF保护
            // 表单登录
            .formLogin(AbstractHttpConfigurer::disable).oauth2ResourceServer(config -> {
                config.jwt(jwtConfigurer -> jwtConfigurer.decoder(jwtDecoder));
                config.bearerTokenResolver(new XddBearerTokenResolver(oAuth2AuthorizationService));
            });
        return http.build();
    }
}
